/// author stevenHu
///
/// created by hujintao
/// created at 2022/3/4cached_network_image/cached_network_image.dart';
// ignore_for_file: constant_identifier_names

import 'dart:async';
import 'dart:ffi';
import 'dart:io';
import 'package:cached_network_image/cached_network_image.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:keyboard_actions/keyboard_actions.dart';
import 'components/image/hk_image.dart';
import 'format_util.dart';
import 'image_enum.dart';

/// 图片加载（支持本地与）带缓存的image 网络图片
Widget hkCachedImage(String url,
    {double? width = 20,
    double? height = 20,
    Widget? placeholder,
    Widget? error,
    BoxFit fit = BoxFit.cover,
    HKImageFormat? format = HKImageFormat.png}) {
  if (url.isEmpty){
    return const SizedBox();
  }
  if (url.startsWith('http') || url.startsWith('https')) {
    return CachedNetworkImage(
        height: height,
        width: width,
        fit: fit,
        placeholder: (
          BuildContext context,
          String url,
        ) =>
            placeholder ?? Container(color: Colors.grey[200]),
        errorWidget: (
          BuildContext context,
          String url,
          dynamic error,
        ) =>
            error ?? const Icon(Icons.error),
        imageUrl: url);
  }

  return LoadAssetImage(
    url,
    height: height ?? 0,
    width: width ?? 0,
    fit: fit,
    format: format ?? HKImageFormat.png,
  );
}
/// 加载本地资源图片
class LoadAssetImage extends StatelessWidget {
  const LoadAssetImage(this.image,
      {Key? key,
        required this.width,
        required this.height,
        this.cacheHeight,
        this.fit,
        this.format = HKImageFormat.png,
        this.color,
        this.needPrefix = true,
        this.prefix = 'images/'})
      : super(key: key);

  final String image;
  final String? prefix;
  final double width;
  final double height;
  final int? cacheHeight;

  /// 是否需要增加前缀
  final bool? needPrefix;
  final BoxFit? fit;
  final HKImageFormat format;
  final Color? color;

  @override
  Widget build(BuildContext context) {
    return Image.asset(
      needPrefix! == true ? '$prefix$image.${format.value}' : image,
      height: height,
      width: width,
      cacheHeight: cacheHeight,
      fit: fit,
      color: color,

      /// 忽略图片语义
      excludeFromSemantics: true,
      colorBlendMode: BlendMode.colorDodge,
    );
  }
}

///黑色线性渐变
hkBlackLinearGradient({bool fromTop = false}) {
  return LinearGradient(
      begin: fromTop ? Alignment.topCenter : Alignment.bottomCenter,
      end: fromTop ? Alignment.bottomCenter : Alignment.topCenter,
      colors: const [
        Colors.black54,
        Colors.black45,
        Colors.black38,
        Colors.black26,
        Colors.black12,
        Colors.transparent
      ]);
}

///带文字的小图标
hkSmallIconText(IconData iconData, var text,
    {double? iconSize = 12,
    double? textSize = 12,
    Color? iconColor = Colors.grey,
    Color? textColor = Colors.grey}) {
  var style = TextStyle(fontSize: textSize, color: textColor);
  if (text is int) {
    text = hkCountFormat(text);
  }
  return [
    Icon(
      iconData,
      color: iconColor,
      size: iconSize,
    ),
    Text(
      ' $text',
      style: style,
    )
  ];
}

///设置间距
SizedBox hkSpace({double height = 1, double width = 1}) {
  return SizedBox(height: height, width: width);
}

/// 设置状态栏主题
hkSetStatusBarDarkTheme(
    {Color color = Colors.transparent, bool isDarkIcon = false}) async {
  if (Platform.isAndroid) {
    if (isDarkIcon) {
      SystemUiOverlayStyle systemUiOverlayStyle = SystemUiOverlayStyle(
          statusBarColor: color, statusBarIconBrightness: Brightness.dark);
      SystemChrome.setSystemUIOverlayStyle(systemUiOverlayStyle);
    } else {
      SystemUiOverlayStyle systemUiOverlayStyle = SystemUiOverlayStyle(
          statusBarColor: color, statusBarIconBrightness: Brightness.light);
      SystemChrome.setSystemUIOverlayStyle(systemUiOverlayStyle);
    }
  }
}

/// 键盘公共配置
KeyboardActionsConfig hkGetKeyboardCommonConfig(
    BuildContext context, List<FocusNode> list,
    {Function? complete, String? title}) {
  return KeyboardActionsConfig(
    keyboardBarColor: Colors.white,
    nextFocus: true,
    actions: List.generate(
        list.length,
        (i) => KeyboardActionsItem(
              focusNode: list[i],
              toolbarButtons: [
                (node) {
                  return GestureDetector(
                    onTap: () {
                      node.unfocus();
                      if (complete != null) {
                        complete();
                      }
                    },
                    child: Padding(
                      padding: const EdgeInsets.only(right: 16.0),
                      child: Text(
                        title ?? '完成',
                        style: TextStyle(
                            color: Theme.of(context).primaryColor,
                            fontWeight: FontWeight.bold),
                      ),
                    ),
                  );
                },
              ],
            )),
  );
}

class ViewUtil {
  ///界面初始化完成:将一个Callback回调转化成Future同步方法（Callback to Future）
  static Future<Void> initFinish() async {
    Completer<Void> completer = Completer();

    WidgetsBinding.instance.addPostFrameCallback((timeStamp) {
      completer.complete();
    });

    return completer.future;
  }
  /*
  使用起来，瞬间简单很多
  void _init() async {
    await ViewUtil.initFinish();
    ///下面可以使用加载弹窗
  }
  */
}


class Gaps {
  /// 水平间隔
  static const Widget hGap4 = SizedBox(width: Dimens.gap_dp4);
  static const Widget hGap5 = SizedBox(width: Dimens.gap_dp5);
  static const Widget hGap8 = SizedBox(width: Dimens.gap_dp8);
  static const Widget hGap10 = SizedBox(width: Dimens.gap_dp10);
  static const Widget hGap12 = SizedBox(width: Dimens.gap_dp12);
  static const Widget hGap15 = SizedBox(width: Dimens.gap_dp15);
  static const Widget hGap16 = SizedBox(width: Dimens.gap_dp16);
  static const Widget hGap32 = SizedBox(width: Dimens.gap_dp32);

  /// 垂直间隔
  static const Widget vGap4 = SizedBox(height: Dimens.gap_dp4);
  static const Widget vGap5 = SizedBox(height: Dimens.gap_dp5);
  static const Widget vGap8 = SizedBox(height: Dimens.gap_dp8);
  static const Widget vGap10 = SizedBox(height: Dimens.gap_dp10);
  static const Widget vGap12 = SizedBox(height: Dimens.gap_dp12);
  static const Widget vGap15 = SizedBox(height: Dimens.gap_dp15);
  static const Widget vGap16 = SizedBox(height: Dimens.gap_dp16);
  static const Widget vGap24 = SizedBox(height: Dimens.gap_dp24);
  static const Widget vGap32 = SizedBox(height: Dimens.gap_dp32);
  static const Widget vGap50 = SizedBox(height: Dimens.gap_dp50);

  static const Widget line = SizedBox(
    height: 0.6,
    width: double.infinity,
    child: DecoratedBox(decoration: BoxDecoration(color: Color(0xFFEEEEEE))),
  );

  // SizeBox
  static Widget sizeBox({double? height}) {
    return SizedBox(height: height ?? Dimens.gap_dp5);
  }

  // 分割线
  static Widget separator(double? height, {Color? lineColor}) {
    return SizedBox(
      height: height ?? 0.6,
      width: double.infinity,
      child: DecoratedBox(
          decoration:
              BoxDecoration(color: lineColor ?? const Color(0xFFEEEEEE))),
    );
  }

  static Widget vLine({double? width, double? height, Color? color}) {
    return Container(
      width: width ?? 2,
      height: height ?? 24.0,
      color: color ?? Colors.white,
    );
  }

  static const Widget empty = SizedBox.shrink();
}

class Dimens {
  static const double font_sp10 = 10.0;
  static const double font_sp12 = 12.0;
  static const double font_sp14 = 14.0;
  static const double font_sp15 = 15.0;
  static const double font_sp16 = 16.0;
  static const double font_sp18 = 18.0;

  static const double gap_dp4 = 4;
  static const double gap_dp5 = 5;
  static const double gap_dp8 = 8;
  static const double gap_dp10 = 10;
  static const double gap_dp12 = 12;
  static const double gap_dp15 = 15;
  static const double gap_dp16 = 16;
  static const double gap_dp24 = 24;
  static const double gap_dp32 = 32;
  static const double gap_dp50 = 50;
}


